<template>
  <div :class="currentClass">
    <img
      :src="currentSrc"
      :style="imageStyle"
      alt=""
      class="message-img"
      @click="handlePreview"
      @error="onError"
    />
  </div>
</template>
<script>
export default {
  props: {
    imageStyle: {
      default: () => ({}),
    },
    src: {
      type: [String],
      default: "",
    },
    defaultSrc: {
      default: require("../../static/icon/icon_no-pictures.png"),
    },
    thumbpath: {
      default: "",
    },
  },
  computed: {
    currentClass() {
      const classArr = ["imagePreview", "message-image"];
      if (this.isError) {
        classArr.push("error");
      }
      return classArr;
    },
  },
  data() {
    return {
      isError: false,
      currentSrc: this.setSrc().replace(/#/g, "%23").replace(/\?/g, "%3F"),
    };
  },
  methods: {
    setSrc() {
      if (!this.src) {
        this.$nextTick(() => {
          this.isError = true;
        });
        return this.thumbpath || this.defaultSrc;
      }
      return this.src;
    },
    handlePreview() {
      this.$viewerApi({
        images: [this.currentSrc],
        options: {
          title: false,
          toolbar: false,
        },
      });
    },
    onError() {
      this.isError = true;
      this.currentSrc = this.defaultSrc;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/chat/messageBox/color";

.imagePreview {
  cursor: pointer;

  &.avatar.error {
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;

    img {
      width: auto !important;
    }
  }

  &.error {
    .message-img {
      width: 100px;
    }
  }

  .message-img {
    width: 200px;
    border-radius: $common-border-radius-2;
  }
}
</style>
